package com.clinic.accessor.db;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.clinic.entity.db.Prescription;
import com.clinic.entity.param.Index;

@Component
public class PrescriptionAccessor extends AbstractDbAccessor<Prescription>{

	public Prescription getPrescriptionById(long id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		criteria.add(Restrictions.eq(Prescription.Columns.PRESCRIPTION_ID, id));
		return uniqueGeneric(criteria);
	}
	
	public List<Prescription> getPrescriptionsByPatientId(long patientId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		criteria.add(Restrictions.eq("patient.userId", patientId));
		criteria.addOrder(Order.desc("date"));
		return listGeneric(criteria, new Index());
	}
	
	public Prescription getPastPrescriptionOfPatient(long patientId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		criteria.add(Restrictions.eq("patient.userId", patientId));
		criteria.addOrder(Order.desc("date"));
		return uniqueGeneric(criteria);
	}
	
	public List<Prescription> getPrescriptionByVisitIndex(int term) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		criteria.add(Restrictions.eq(Prescription.Columns.VISIT_INDEX, term));
		criteria.addOrder(Order.desc("date"));
		return listGeneric(criteria, new Index());
	}

	public List<Prescription> getPrescriptionsByRootPrescriptionId(long rootPrescriptionId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		criteria.add(Restrictions.eq("rootPrescription." + Prescription.Columns.PRESCRIPTION_ID, rootPrescriptionId));
		criteria.addOrder(Order.desc("date"));
		return listGeneric(criteria, new Index());
	}
	
	public List<Prescription> getPrescriptions(Index index) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		criteria.addOrder(Order.desc("date"));
		return listGeneric(criteria, index);
	}
	
	public int countPrescriptions() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		return getCount(criteria);
	}
	
	public List<Prescription> getAllPrescriptions() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Prescription.class);
		criteria.add(Restrictions.gt(Prescription.Columns.PRESCRIPTION_ID, 0));
		criteria.addOrder(Order.desc("date"));
		return listGeneric(criteria, new Index());
	}
}